package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IEmpTrainDAO;
import org.jsola.hr.dto.EmpTrainAddDTO;
import org.jsola.hr.dto.EmpTrainDTO;
import org.jsola.hr.dto.EmpTrainUpdateDTO;
import org.jsola.hr.entity.EmpTrainDO;
import org.jsola.hr.query.EmpTrainQuery;
import org.jsola.hr.service.IEmpTrainService;
import org.jsola.hr.vo.EmpTrainListVO;
import org.jsola.hr.vo.EmpTrainVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrEmpTrainServiceImpl")
public class EmpTrainServiceImpl implements IEmpTrainService {

    @Autowired
    private IEmpTrainDAO empTrainDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpTrainVO save(EmpTrainAddDTO empTrainAddDTO, TokenUser tokenUser) {
        // 转DO
        EmpTrainDO empTrainDO = empTrainAddDTO.to(EmpTrainDO.class);

        // 校验员工和公司
        checkEmpAndCompany(empTrainDO.getEmpId(), empTrainDO.getCompanyId(), tokenUser.getSiteId());

        // 保存
        empTrainDO = save(empTrainDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return empTrainDO.to(EmpTrainVO.class);
    }

    /**
     * 校验员工和公司
     *
     * @param empId     员工id
     * @param companyId 公司id
     * @param siteId    站点
     */
    private void checkEmpAndCompany(String empId, String companyId, String siteId) {
        ParamException.hasLength(empId, "员工id不能为空");
        ParamException.hasLength(companyId, "公司id不能为空");
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(EmpTrainUpdateDTO empTrainUpdateDTO, TokenUser tokenUser) {
        //转DO
        EmpTrainDO empTrainDO = empTrainUpdateDTO.to(EmpTrainDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(empTrainDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... empTrainIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) empTrainIds);
    }


    @Override
    public EmpTrainVO selectById(String empTrainId, String siteId) {
        EmpTrainDO empTrainDO = selectDOById(empTrainId, siteId);
        if (empTrainDO == null) {
            return null;
        }
        return empTrainDO.to(EmpTrainVO.class);
    }

    @Override
    public List<EmpTrainListVO> select(EmpTrainQuery empTrainQuery, String siteId) {
        List<EmpTrainDO> empTrainDOList = selectDO(empTrainQuery, siteId);
        if(CollectionUtils.isEmpty(empTrainDOList)) {
            return empTrainDOList == null ? null : new ArrayList<>();
        }
        return empTrainDOList.stream()
                .map(empTrainDO -> empTrainDO.to(EmpTrainListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(EmpTrainQuery empTrainQuery, String siteId) {
        Example example = buildExample(empTrainQuery,siteId);
        return empTrainDAO.selectCountByExample(example);
    }

    @Override
    public Page<EmpTrainListVO> selectPage(EmpTrainQuery empTrainQuery, String siteId) {
        Example example = buildExample(empTrainQuery,siteId);
        Page<EmpTrainDO> page = empTrainDAO.selectPageByExample(example,
                empTrainQuery.getPageNo(),
                empTrainQuery.getPageSize());

        return page.to(EmpTrainListVO.class);
    }

    @Override
    public EmpTrainDO selectDOById(String empTrainId, String siteId) {
        return listById(empTrainId, siteId);
    }

    @Override
    public List<EmpTrainDO> selectDO(EmpTrainQuery empTrainQuery, String siteId) {
        Example example = buildExample(empTrainQuery,siteId);
        return empTrainDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void deleteByCompanyId(String companyId, TokenUser tokenUser) {
        Example example = new Example(EmpTrainDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        // 逻辑删除
        List<EmpTrainDO> list = empTrainDAO.selectByExample(example);
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void publishEmpTrainList(List<EmpTrainDTO> empTrainList, String companyId, String empId, TokenUser tokenUser) {
        // 删除某个员工所有的
        deleteByEmpId(empId, tokenUser);

        if (CollectionUtils.isEmpty(empTrainList)) {
            return;
        }

        empTrainList.forEach(
                empTrainDTO -> {
                    empTrainDTO.setCompanyId(companyId);
                    empTrainDTO.setEmpId(empId);
                    // 新增
                    EmpTrainAddDTO empTrainAddDTO = empTrainDTO.to(EmpTrainAddDTO.class);
                    save(empTrainAddDTO, tokenUser);
                }
        );
    }

    @Override
    public List<EmpTrainDO> listByEmpId(String empId, String siteId) {
        Example example = new Example(EmpTrainDO.class);
        example.and()
                .andEqualTo("empId", empId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        example.orderBy("gmtCreate");
        //
        return empTrainDAO.selectByExample(example);
    }

    /**
     * 删除某个员工所有的
     *
     * @param empId     员工id
     * @param tokenUser 当前用户
     */
    private void deleteByEmpId(String empId, TokenUser tokenUser) {
        // 逻辑删除
        List<EmpTrainDO> list = listByEmpId(empId, tokenUser.getSiteId());
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }


    /**
     * 根据查询参数，构建example

     * @param empTrainQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(EmpTrainQuery empTrainQuery, String siteId) {
        Example example = new Example(EmpTrainDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (empTrainQuery.getEmpId() != null) {
            example.and().andLike("empId", "%" + empTrainQuery.getEmpId() + "%");
        }
        if (empTrainQuery.getTrainCourse() != null) {
            example.and().andLike("trainCourse", "%" + empTrainQuery.getTrainCourse() + "%");
        }
        if (empTrainQuery.getStartTimeStart() != null &&
                empTrainQuery.getStartTimeEnd() != null) {
            example.and().andBetween("startTime", empTrainQuery.getStartTimeStart(),
                    empTrainQuery.getStartTimeEnd());
        }
        if (empTrainQuery.getEndTimeStart() != null &&
                empTrainQuery.getEndTimeEnd() != null) {
            example.and().andBetween("endTime", empTrainQuery.getEndTimeStart(),
                    empTrainQuery.getEndTimeEnd());
        }
        if (empTrainQuery.getTrainDuration() != null) {
            example.and().andLike("trainDuration", "%" + empTrainQuery.getTrainDuration() + "%");
        }
        if (empTrainQuery.getTrainOrgName() != null) {
            example.and().andLike("trainOrgName", "%" + empTrainQuery.getTrainOrgName() + "%");
        }
        if (empTrainQuery.getAssessResult() != null) {
            example.and().andLike("assessResult", "%" + empTrainQuery.getAssessResult() + "%");
        }
        if (empTrainQuery.getTrainAddress() != null) {
            example.and().andLike("trainAddress", "%" + empTrainQuery.getTrainAddress() + "%");
        }
        if (empTrainQuery.getTrainMode() != null) {
            example.and().andLike("trainMode", "%" + empTrainQuery.getTrainMode() + "%");
        }
        if (empTrainQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", empTrainQuery.getCompanyId());
        }
        if (empTrainQuery.getGmtCreateStart() != null &&
                empTrainQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", empTrainQuery.getGmtCreateStart(),
                    empTrainQuery.getGmtCreateEnd());
        }
        if (empTrainQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + empTrainQuery.getCreateUserId() + "%");
        }
        if (empTrainQuery.getGmtModifiedStart() != null &&
                empTrainQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", empTrainQuery.getGmtModifiedStart(),
                    empTrainQuery.getGmtModifiedEnd());
        }
        if (empTrainQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + empTrainQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,empTrainQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer deleteEmpTrain(TokenUser tokenUser, String empTrainId){
        return empTrainDAO.deleteByPrimaryKey(empTrainId);
    }
}




